package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    ApArticleContentMapper apArticleContentMapper;

    @Autowired
    AuthorMapper authorMapper;

    @Autowired
    Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    private String prefix;

    @Override
    public void generateArticlePage(Long articleId) {
        //1.根据文章id 查询文章信息  文章内容 文章作者信息
        log.info("静态页生成方法被触发 ==== articleId ==>{}", articleId);
        ApArticle apArticle = apArticleMapper.selectById(articleId);

        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers
                .<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleId));
        if (apArticleContent == null || StringUtils.isBlank(apArticleContent.getContent())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<Map> content = JSON.parseArray(apArticleContent.getContent(), Map.class);
        //3. 准备数据模型
        Map<String, Object> map = new HashMap<>();
        map.put("authorApUserId", apArticle.getAuthorId());
        map.put("article", apArticle);
        map.put("content", content);
        //2. 获取模板
        try {
            Template template = configuration.getTemplate("article.ftl");
            //4. 调用
            StringWriter stringWriter = new StringWriter();
            template.process(map, stringWriter);
            //输入流
            ByteArrayInputStream inputStream = new ByteArrayInputStream(stringWriter.toString().getBytes());
            //生成页面把html文件上传到minio中
            String htmlPath = fileStorageService.store(prefix, apArticleContent.getContent() + ".html", "text/html", inputStream);
            System.out.println(htmlPath);
            //5.修改ap_article表，保存static_url字段
            apArticle.setStaticUrl(htmlPath);
            apArticleMapper.updateById(apArticle);
            log.info("页面静态化 成功  页面路径:{}",htmlPath);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("页面静态化生成失败,原因:{}", e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
